import logging
import os
from concurrent_log_handler import ConcurrentTimedRotatingFileHandler


def get_logger(name: str = None, level=logging.INFO):
    if name is None:
        logger = logging.getLogger(__name__)
    else:
        logger = logging.getLogger(name)

    logger.setLevel(level)

    if not logger.handlers:
        if not os.path.exists("logs"):
            os.makedirs("logs")

        console = logging.StreamHandler()
        file_handler = ConcurrentTimedRotatingFileHandler(
            filename="logs/spider_run.log",
            when="midnight",
            interval=1,
            backupCount=14,
            maxBytes=1024 * 1024 * 30,
            encoding="utf-8",
            delay=True,
            use_gzip=True,
            chmod=755,
        )
        formatter = logging.Formatter(
            "%(asctime)s - %(module)s - %(funcName)s - line:%(lineno)d - %(levelname)s - %(message)s"
        )

        console.setFormatter(formatter)
        file_handler.setFormatter(formatter)
        logger.addHandler(console)  # 将日志输出至屏幕
        logger.addHandler(file_handler)  # 将日志输出至文件

    return logger
